package com.stox.ui.javafx.charting.model.plot;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.stox.dto.AbstractModel;
import com.stox.dto.Bar;
import com.stox.dto.IndicatorModel;
import com.stox.indicator.Indicator;
import com.stox.indicator.MACD;
import com.stox.indicator.MACD.Unit;
import com.stox.ui.javafx.charting.model.uiunit.MACDUiUnit;
import com.stox.ui.javafx.charting.widget.Chart;

@Component("macdPlot")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class MACDPlot extends AbstractPlot<Unit, Chart<MACDPlot>, MACDUiUnit, MACDPlot> {

	public MACDPlot(AbstractModel model) {
		super(model);
	}

	/**
	 * TODO : This method should be in AbstractPlot
	 */
	@Override
	protected void createUiUnits() {
		for(int i = 0; i < getData().size(); i++)			
			getUiUnits().add(new MACDUiUnit(getData().get(i),this,i));
	}

	/**
	 * TODO : This method should be in AbstractPlot
	 */
	@Override
	public void paint() {
		for(int index = getChart().getChartingView().getEndIndex()-1; 
				index >= getChart().getChartingView().getStartIndex(); index--) {
			getUiUnits().get(index).paint();
		}
	}
	
	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void update() {
		AbstractPrimaryPlot frontPlot = getChart().getChartingView().getPrimaryChart().getFrontPlot();
		List<Bar> bars = frontPlot.getData();
		if(frontPlot.isDataChanged() || bars.size() != getData().size()){
			IndicatorModel indicatorModel = (IndicatorModel)getModel();
			Indicator<Object, MACD.Unit> indicator = indicatorModel.getIndicator();
			setData(Arrays.asList(indicator.getValues(indicatorModel.getConfiguration(), bars)));
		}
		super.update();
		for(int index = getChart().getChartingView().getEndIndex()-1; 
				index >= getChart().getChartingView().getStartIndex(); index--) {
			Unit unit = getData().get(index);
			if(null == unit) continue;
			double high = Math.max(Math.max(unit.getHist(), unit.getMacd()), unit.getSignal());
			double low = Math.min(Math.min(unit.getHist(), unit.getMacd()), unit.getSignal());
			if(highest < high) highest = high;
			if(lowest > low) lowest = low;
		}
		for(int index = getChart().getChartingView().getEndIndex()-1; 
				index >= getChart().getChartingView().getStartIndex(); index--) {
			getUiUnits().get(index).update();
		}
	}
}
